<%@ page language="java" contentType="application/json;charset=UTF-8" %>
<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@ page import="java.util.*" %>
<%@ page import="javax.servlet.http.HttpServletResponse" %>
<%
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        int apiIndex = requestURI.indexOf("/api");
        
        if (apiIndex < 0) {
            // 如果没有 /api 前缀，返回错误
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json;charset=UTF-8");
            String errorMsg = "{\"code\":400,\"msg\":\"无效的代理请求，缺少 /api 前缀\"}";
            response.getOutputStream().write(errorMsg.getBytes("UTF-8"));
        } else {
            String path = requestURI.substring(apiIndex + 4); // 去掉 /api 前缀
            
            // 构建后端服务完整URL
            // 注意：后端服务不需要 /download 前缀，所以直接使用 path
            String backendUrl = "http://localhost:8088" + path;
            
            // 如果有查询参数，加上去
            String queryString = request.getQueryString();
            if (queryString != null && !queryString.isEmpty()) {
                backendUrl += "?" + queryString;
            }
            
            // 记录日志
            System.out.println("Proxy Request: " + backendUrl);
            
            // 创建URL连接
            URL url = new URL(backendUrl);
            conn = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法
            conn.setRequestMethod(request.getMethod());
            
            // 复制请求头
            Enumeration<String> headers = request.getHeaderNames();
            while (headers.hasMoreElements()) {
                String headerName = headers.nextElement();
                String headerValue = request.getHeader(headerName);
                // 避免复制可能导致问题的头，例如 Content-Length
                if (!"Content-Length".equalsIgnoreCase(headerName)) {
                    conn.setRequestProperty(headerName, headerValue);
                }
            }
            
            // 设置超时
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            
            // 如果是POST或PUT请求，复制请求体
            if ("POST".equalsIgnoreCase(request.getMethod()) || "PUT".equalsIgnoreCase(request.getMethod())) {
                conn.setDoOutput(true);
                outputStream = conn.getOutputStream();
                InputStream requestInputStream = request.getInputStream();
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = requestInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }
            
            // 发送请求
            conn.connect();
            
            // 获取响应状态码
            int responseCode = conn.getResponseCode();
            response.setStatus(responseCode);
            
            // 复制响应头
            Map<String, List<String>> responseHeaders = conn.getHeaderFields();
            for (String headerName : responseHeaders.keySet()) {
                if (headerName != null) {
                    for (String headerValue : responseHeaders.get(headerName)) {
                        response.addHeader(headerName, headerValue);
                    }
                }
            }
            
            // 读取响应内容并直接写入响应流
            if (responseCode >= 200 && responseCode < 300) {
                inputStream = conn.getInputStream();
            } else {
                inputStream = conn.getErrorStream();
            }
            
            if (inputStream != null) {
                // 使用 response.getOutputStream() 直接写入响应
                OutputStream responseOutputStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    responseOutputStream.write(buffer, 0, bytesRead);
                }
                responseOutputStream.flush();
                responseOutputStream.close();
            }
        }
        
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("application/json;charset=UTF-8");
        String errorMsg = "{\"code\":500,\"msg\":\"代理错误: " + e.getMessage() + "\"}";
        try {
            response.getOutputStream().write(errorMsg.getBytes("UTF-8"));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        if (outputStream != null) {
            try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
%>